﻿using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using CCTool.Scripts.Manager;
using CCTool.Scripts.ToolManagers;
using CCTool.Scripts.ToolManagers.Extensions;
using CCTool.Scripts.ToolManagers.Managers;
using NPOI.OpenXmlFormats.Vml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CCTool.Scripts.GHApp.QT
{
    /// <summary>
    /// Interaction logic for CreateGHFQ.xaml
    /// </summary>
    public partial class CreateGHFQ : ArcGIS.Desktop.Framework.Controls.ProWindow
    {
        // 工具设置标签
        readonly string toolSet = "CreateGHFQ";

        public CreateGHFQ()
        {
            InitializeComponent();

            textFQPath.Text = BaseTool.ReadValueFromReg(toolSet, "fqPath");
        }

        // 定义一个进度框
        private ProcessWindow processwindow = null;
        string tool_name = "国空规划分区[简单版]";

        private void combox_kfbj_DropDown(object sender, EventArgs e)
        {
            UITool.AddFeatureLayersToComboxPlus(combox_kfbj);
        }

        private void combox_jbnt_DropDown(object sender, EventArgs e)
        {
            UITool.AddFeatureLayersToComboxPlus(combox_jbnt);
        }

        private void combox_sthx_DropDown(object sender, EventArgs e)
        {
            UITool.AddFeatureLayersToComboxPlus(combox_sthx);
        }

        private void combox_yd_DropDown(object sender, EventArgs e)
        {
            UITool.AddFeatureLayersToComboxPlus(combox_yd);
        }

        private void openFcButton_Click(object sender, RoutedEventArgs e)
        {
            textFQPath.Text = UITool.SaveDialogFeatureClass();
        }

        private async void btn_go_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 获取默认数据库
                string defGDB = Project.Current.DefaultGeodatabasePath;
                string defFolder = Project.Current.HomeFolderPath;

                string yd = combox_yd.ComboxText();
                string bmField = combox_bmField.ComboxText();
                // 获取三线
                string kfbj = combox_kfbj.ComboxText();
                string jbnt = combox_jbnt.ComboxText();
                string sthx = combox_sthx.ComboxText();

                string fqPath = textFQPath.Text;

                // 判断参数是否选择完全
                if (yd == "" || bmField == "" || fqPath == "")
                {
                    MessageBox.Show("有必选参数为空！！！");
                    return;
                }

                // 写入本地
                BaseTool.WriteValueToReg(toolSet, "fqPath", fqPath);

                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);

                Close();
                await QueuedTask.Run(() =>
                {
                    pw.AddMessageStart("检查数据");
                    // 检查数据
                    List<string> errs = CheckData(yd, bmField);
                    // 打印错误
                    if (errs.Count > 0)
                    {
                        foreach (var err in errs)
                        {
                            pw.AddMessageMiddle(10, err, Brushes.Red);
                        }
                        return;
                    }

                    pw.AddMessageMiddle(10, "按用地编码初步分类");
                    string excelPath = @$"{defFolder}\国空规划分区.xlsx";
                    DirTool.CopyResourceFile(@"CCTool.Data.Excel.杂七杂八.国空规划分区.xlsx", excelPath);

                    string bm = "GHFQDM";
                    string mc = "GHFQMC";
                    // 复制一个要素类
                    Arcpy.CopyFeatures(yd, fqPath);
                    Arcpy.AddField(fqPath, bm, "TEXT", "规划分区代码");
                    Arcpy.AddField(fqPath, mc, "TEXT", "规划分区名称");
                    // 按用地编码初步分类
                    ComboTool.AttributeMapper(fqPath, bmField, mc, $@"{excelPath}\sheet1$" );


                    string zone = $@"{defGDB}\zone";
                    string sthx_clip = $@"{defGDB}\sthx_clip";
                    string jbnt_clip = $@"{defGDB}\jbnt_clip";
                    string kfbj_clip = $@"{defGDB}\kfbj_clip";

                    string idenntity_kfbj = $@"{defGDB}\idenntity_kfbj";
                    string idenntity_sthx = $@"{defGDB}\idenntity_sthx";
                    string idenntity_jbnt = $@"{defGDB}\idenntity_jbnt";

                    // 生成范围
                    Arcpy.Dissolve(yd, zone);

                    // 设置一下当前生成的结果
                    string initYD = fqPath;


                    // 叠加生态保护红线
                    if (sthx != "")
                    {
                        pw.AddMessageMiddle(10, "叠加生态保护红线");
                        Arcpy.Clip(sthx, zone, sthx_clip);
                        // 如果范围内没有要素，就跳过
                        if (sthx_clip.GetFeatureCount() == 0)
                        {
                            return;
                        }

                        Arcpy.AddField(sthx_clip, mc);
                        Arcpy.CalculateField(sthx_clip, mc, "'生态保护区'");
                        Arcpy.DeleteField(sthx_clip, mc, "KEEP_FIELDS");
                        Arcpy.Update(initYD, sthx_clip, idenntity_sthx);
                        // 更新当前结果
                        initYD = idenntity_sthx;
                    }


                    // 叠加永久基本农田
                    if (jbnt != "")
                    {
                        pw.AddMessageMiddle(10, "叠加永久基本农田");
                        Arcpy.Clip(jbnt, zone, jbnt_clip);
                        // 如果范围内没有要素，就跳过
                        if (jbnt_clip.GetFeatureCount() == 0)
                        {
                            return;
                        }

                        Arcpy.AddField(jbnt_clip, mc);
                        Arcpy.CalculateField(jbnt_clip, mc, "'农田保护区'");
                        Arcpy.DeleteField(jbnt_clip, mc, "KEEP_FIELDS");
                        Arcpy.Update(initYD, jbnt_clip, idenntity_jbnt);
                        // 更新当前结果
                        initYD = idenntity_jbnt;
                    }


                    // 叠加城镇开发边界
                    if (kfbj != "")
                    {
                        pw.AddMessageMiddle(10, "叠加城镇开发边界");
                        Arcpy.Clip(kfbj, zone, kfbj_clip);
                        // 如果范围内没有要素，就跳过
                        if (kfbj_clip.GetFeatureCount() == 0)
                        {
                            return;
                        }

                        Arcpy.AddField(kfbj_clip, mc);
                        Arcpy.CalculateField(kfbj_clip, mc, "'城镇发展区'");
                        Arcpy.DeleteField(kfbj_clip, mc, "KEEP_FIELDS");
                        Arcpy.Update(initYD, kfbj_clip, idenntity_kfbj);
                        // 更新当前结果
                        initYD = idenntity_kfbj;
                    }

                    if (initYD != fqPath)
                    {
                        Arcpy.CopyFeatures(initYD, fqPath, true);
                    }

                    // 计算分区编码
                    string code = "def ss(a):\r\n    dict = {'生态保护区':'100','生态控制区':'200','农田保护区':'300','城镇发展区':'400','乡村发展区':'500'}\r\n    if a in dict:\r\n        return dict[a];\r\n    else:\r\n        return ''";
                    Arcpy.CalculateField(fqPath, bm, $"ss(!{mc}!)", code);
                    

                    // 删除中间数据
                    File.Delete(excelPath);
                    Arcpy.Delect(jbnt_clip);
                    Arcpy.Delect(sthx_clip);
                    Arcpy.Delect(kfbj_clip);
                    Arcpy.Delect(idenntity_sthx);
                    Arcpy.Delect(idenntity_kfbj);
                    Arcpy.Delect(idenntity_jbnt);
                    Arcpy.Delect(zone);

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private void btn_help_Click(object sender, RoutedEventArgs e)
        {
            string url = "https://blog.csdn.net/xcc34452366/article/details/137541213";
            UITool.Link2Web(url);
        }


        private async void CheckJbnt(Dictionary<string, SolidColorBrush> error, Button btn)
        {
            // 隐藏错误标记
            btn.Visibility = Visibility.Hidden;
            error.Clear();

            // 三调图层
            string in_data = combox_jbnt.ComboxText();

            await QueuedTask.Run(() =>
            {
                if (in_data != "")
                {
                    // 检查字段值是否存在
                    string result_value = CheckTool.IsHaveFieldInLayer(in_data, "DLMC");
                    if (result_value != "")
                    {
                        error.Add(result_value, Brushes.Red);
                    }
                    else
                    {
                        // 检查字段值是否为空【KCXS】
                        string fieldEmptyResult = CheckTool.CheckFieldValueEmpty(in_data, "KCXS", "DLMC IN ('旱地', '水田', '水浇地')");
                        if (fieldEmptyResult != "")
                        {
                            error.Add(fieldEmptyResult, Brushes.Red);
                        }
                    }
                }
            });

            if (error.Count > 0)
            {
                btn.Visibility = Visibility.Visible;
            }
        }




        private List<string> CheckData(string yd, string bmField)
        {
            List<string> result = new List<string>();

            // 检查字段值是否存在

            string result_value = CheckTool.CheckFieldValueSpace(yd, bmField);

            return result;
        }

        private void combox_bmField_DropDown(object sender, EventArgs e)
        {
            UITool.AddTextFieldsToComboxPlus(combox_yd.ComboxText(), combox_bmField);
        }
    }
}
